<template>
   <div class="box">
      <div class="box_top">
         <el-select class="box_input" v-model="address" filterable remote @change="changeAddress" reserve-keyword
            placeholder="请输入地点" remote-show-suffix :remote-method="remoteMethod" :loading="loading"
            style="width: 240px">
            <el-option v-for="item in addressList" :key="item.id" :label="item.title" :value="item.id" />
         </el-select>

         <el-select v-model="addressStr.floor" placeholder="请选择楼层" style="width: 130px; margin-left: 20px"
            @change="updateFloor">
            <el-option v-for="option in floorOptions" :key="option.label" :label="option.value"
               :value="option.label"></el-option>
         </el-select>
      </div>
      <vqqmap :key="componentKey" v-model="addressStr" :options="options" @error="handleMapError"></vqqmap>
   </div>
</template>
<script setup>
const emit = defineEmits(["changeAddress"]);
import { jsonp } from "vue-jsonp";
import vqqmap from "vue-qqmap";
import { usePublicDataStore } from "@/stores";
const publicDataStore = usePublicDataStore();
const componentKey = ref(0);
let addressList = ref([]);
const address = ref("");
const loading = ref(false);
const prop = defineProps({
   addressObj: {
      type: Object,
      default: {
         floor: null,
         lat: "30.584066",
         lng: "104.060845",
         address: "四川省成都市武侯区交子大道88号(金融城地铁站A口步行460米) 负一层",
         province: "四川省",
         city: "成都市",
         district: "武侯区",
      },
   },
   status: {
      type: [Number, String],
      default: 0,
   },
});

// 定义楼层选项
const floorOptions = [
   { value: "负一楼", label: "负一楼" },
   { value: "负二楼", label: "负二楼" },
   { value: "负三楼", label: "负三楼" },
   { value: "负四楼", label: "负四楼" },
   { value: "负五楼", label: "负五楼" },
];

let options = reactive({
   key: publicDataStore.qqMapKey,
   width: "100%",
   showBorder: false,
   showHeader: false,
   showFooter: false,
   zoom: 18,
});

let addressStr = ref(prop.addressObj);

// 解析地址函数，将完整地址拆分为省市区
const parseAddress = (fullAddress) => {
   if (!fullAddress) return;

   // 移除楼层信息（如果存在）
   const addressWithoutFloor = fullAddress.split(" ")[0];

   // 常见的省级行政区
   const provinces = [
      '北京市', '天津市', '上海市', '重庆市', '河北省', '山西省', '辽宁省', '吉林省',
      '黑龙江省', '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', '河南省',
      '湖北省', '湖南省', '广东省', '海南省', '四川省', '贵州省', '云南省', '陕西省',
      '甘肃省', '青海省', '台湾省', '内蒙古自治区', '广西壮族自治区', '西藏自治区',
      '宁夏回族自治区', '新疆维吾尔自治区', '香港特别行政区', '澳门特别行政区'
   ];

   // 提取省份
   let province = '';
   let city = '';
   let district = '';

   // 尝试匹配省份
   for (const p of provinces) {
      if (addressWithoutFloor.startsWith(p) || addressWithoutFloor.startsWith(p.replace('省', '').replace('市', '').replace('自治区', ''))) {
         province = p;
         break;
      }
   }

   // 如果找到省份，继续解析城市和区域
   if (province) {
      // 移除省份部分
      const afterProvince = addressWithoutFloor.substring(province.length);

      // 尝试提取城市（假设城市以"市"结尾）
      const cityMatch = afterProvince.match(/^(.*?市)/);
      if (cityMatch) {
         city = cityMatch[1];

         // 提取区域（假设区域以"区"、"县"、"市"等结尾）
         const afterCity = afterProvince.substring(city.length);
         const districtMatch = afterCity.match(/^(.*?[区县市旗])/);
         if (districtMatch) {
            district = districtMatch[1];
         }
      }
   }

   // 如果正则匹配失败，使用简单的回退解析
   if (!province || !city) {
      const parts = addressWithoutFloor.split(/省|市|自治区/);
      if (parts.length >= 3) {
         province = parts[0] + (addressWithoutFloor.includes('省') ? '省' : addressWithoutFloor.includes('自治区') ? '自治区' : '市');
         city = parts[1] + '市';
         const districtParts = parts[2].split(/区|县|旗/);
         if (districtParts.length >= 2) {
            district = districtParts[0] + (parts[2].includes('区') ? '区' : parts[2].includes('县') ? '县' : '旗');
         }
      }
   }

   // 更新地址对象
   if (province) addressStr.value.province = province;
   if (city) addressStr.value.city = city;
   if (district) addressStr.value.district = district;

   console.log('地址解析结果:', { province, city, district });
};

const handleMapError = () => {
   // 地图加载错误时，尝试解析地址
   parseAddress(addressStr.value.address);
};

// 添加地址到下拉列表
const addAddressToList = (addressText) => {
   if (!addressText) return;

   // 移除楼层部分
   const addressWithoutFloor = addressText.split(" ")[0];

   // 避免重复添加
   const existingAddress = addressList.value.find(item => item.title === addressWithoutFloor);
   if (existingAddress) {
      address.value = existingAddress.id;
      return;
   }

   // 创建唯一ID
   const uniqueId = 'manual_' + Date.now();

   // 添加到列表
   addressList.value.unshift({
      id: uniqueId,
      title: addressWithoutFloor,
      address: addressWithoutFloor,
      province: addressStr.value.province || '',
      city: addressStr.value.city || '',
      district: addressStr.value.district || '',
      location: {
         lat: addressStr.value.lat || '',
         lng: addressStr.value.lng || ''
      }
   });

   // 设置为选中
   address.value = uniqueId;
};

const remoteMethod = (query, status) => {
   if (query) {
      loading.value = true;
      let url = "https://apis.map.qq.com/ws/place/v1/suggestion/?region=成都";
      jsonp(url, {
         key: publicDataStore.qqMapKey,
         keyword: query,
         output: "jsonp",
      }).then((res) => {
         loading.value = false;
         if (res.data && Array.isArray(res.data)) {
            addressList.value = res.data;
            if (status) {
               if (res.data.length > 0) {
                  address.value = res.data[0]?.id;
                  addressStr.value.province = res.data[0].province;
                  addressStr.value.city = res.data[0].city;
                  addressStr.value.district = res.data[0].district;
               } else {
                  // 没有搜索结果时，添加当前地址
                  addAddressToList(query);
                  parseAddress(query);
               }
            }
         } else {
            // API返回格式错误，添加当前地址
            addAddressToList(query);
            parseAddress(query);
         }
      }).catch(() => {
         loading.value = false;
         // API请求失败时，添加当前地址到列表
         addAddressToList(query);
         parseAddress(query);
      });
   } else {
      options.value = [];
   }
};

const changeAddress = (e) => {
   let { floor } = addressStr.value;
   const selectedAddress = addressList.value.find((item) => item.id == e);
   if (selectedAddress) {
      addressStr.value = { ...selectedAddress };
      addressStr.value.floor = floor;
      addressStr.value.address = addressStr.value.address + " " + addressStr.value.floor;

      if (selectedAddress.location) {
         const { lat, lng } = selectedAddress.location;
         if (lat && lng) {
            addressStr.value.lat = lat;
            addressStr.value.lng = lng;
         }
      }

      componentKey.value += 1;
   }
};

const updateFloor = (e) => {
   // 将地址按空格分割成数组
   const addressParts = addressStr.value.address.split(" ");
   if (addressParts.length < 2) {
      addressParts.push(e);
   } else {
      addressParts[addressParts.length - 1] = e;
   }

   // 重新拼接成完整的地址字符串
   addressStr.value.address = addressParts.join(" ");
};

watch(
   addressStr,
   (newVal, oldVal) => {
      emit("changeAddress", newVal);
   },
   {
      deep: true,
   }
);

onMounted(() => {
   // 如果初始化时已有地址，尝试解析
   if (addressStr.value && addressStr.value.address) {
      parseAddress(addressStr.value.address);

      // 在编辑模式下，添加当前地址到下拉选项
      if (prop.status == 1 && addressStr.value.address) {
         addAddressToList(addressStr.value.address);
      }
   }
});

if (prop.status == 0) {
   addressList.value = [];
} else {
   // 编辑模式
   addressStr.value.floor = prop.addressObj.address.split(" ")[1] || "";

   if (prop.addressObj && prop.addressObj.address) {
      // 解析地址
      parseAddress(prop.addressObj.address);

      // 添加当前地址到下拉选项
      const addressWithoutFloor = prop.addressObj.address.split(" ")[0];
      addAddressToList(addressWithoutFloor);

      // 尝试通过API搜索地址
      remoteMethod(addressWithoutFloor, 1);
   }
}
</script>
<style lang="scss" scoped>
.box {
   &_input {
      margin-bottom: 10px;
   }

   &_top {
      display: flex;
   }
}
</style>
